<template>
  <view class="container">
    <view class="header">您好，欢迎登录！</view>
    <view class="login-type-switch">
      <view class="switch-container">
        <view
          :class="['switch-option', loginForm.role === 'USER' ? 'active' : '']"
          @tap="switchRole('USER')"
        >
          用户登录
        </view>
        <view
          :class="['switch-option', loginForm.role === 'EMPLOY' ? 'active' : '']"
          @tap="switchRole('EMPLOY')"
        >
          企业登录
        </view>
      </view>
    </view>

    <view class="form">
      <view class="input-group">
        <text class="label">{{ loginForm.role === 'USER' ? '邮箱' : '企业邮箱' }}</text>
        <input
          type="text"
          v-model="loginForm.email"
          :placeholder="loginForm.role === 'USER' ? '请输入邮箱' : '请输入企业邮箱'"
          @blur="validateEmail"
        />
        <text class="error-message" v-if="errors.email">{{ errors.email }}</text>
      </view>

      <view class="input-group">
        <text class="label">验证码</text>
        <view class="code-wrapper">
          <input
            type="text"
            v-model="loginForm.code"
            placeholder="请输入验证码"
            @blur="validateCode"
            style="border: none;"
          />
          <view
            class="code-btn"
            @tap="getCode"
            :disabled="counting"
          >
            {{ counting ? `${countdown}s` : '获取验证码' }}
          </view>
        </view>
        <text class="error-message" v-if="errors.code">{{ errors.code }}</text>
      </view>
    </view>

    <button class="login-btn" @tap="handleLogin">登录</button>

    <view class="ques">
      <view @tap="goForgot">忘记密码</view>
      <view class="divider">|</view>
      <view @tap="goRegister" class="register-link">去注册</view>
    </view>

    <view class="footer">
      登录即表明同意隐私协议和用户服务协议
    </view>
  </view>
</template>

<script>
import { mapActions } from 'vuex'
import { sendCode } from '@/api/login.js'  
export default {
  data() {
    return {
      loginForm: {
        role: 'USER',
        email: '',
        code: ''
      },
      errors: {
        email: '',
        code: ''
      },
      countdown: 60,
      counting: false,
      timer: null
    }
  },
  methods: {
    ...mapActions(['codeLogin']),   

    switchRole(role) {
      this.loginForm.role = role
      this.clearErrors()
      this.loginForm.email = ''
      this.loginForm.code = ''
      this.resetCountdown()
    },

    validateEmail() {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!this.loginForm.email) {
        this.errors.email = this.loginForm.role === 'USER' ? '请输入邮箱' : '请输入企业邮箱'
        return false
      } else if (!emailRegex.test(this.loginForm.email)) {
        this.errors.email = '邮箱格式不正确'
        return false
      } else {
        this.errors.email = ''
        return true
      }
    },

    validateCode() {
      if (!this.loginForm.code) {
        this.errors.code = '请输入验证码'
        return false
      } else if (this.loginForm.code.length < 4) {
        this.errors.code = '验证码格式不正确'
        return false
      } else {
        this.errors.code = ''
        return true
      }
    },

    async getCode() {
      if (!this.validateEmail()) return
      if (this.counting) return

      try {
        uni.showLoading({ title: '发送中...' })
        const res = await sendCode(this.loginForm.email)
        uni.hideLoading()

        if (res.code === 200) {
          uni.showToast({ title: '验证码已发送', icon: 'success' })
          this.startCountdown()
        } else {
          uni.showToast({ title: res.data.msg || '发送失败', icon: 'none' })
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({ title: '发送失败，请重试', icon: 'none' })
      }
    },

    startCountdown() {
      this.counting = true
      this.timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) this.resetCountdown()
      }, 1000)
    },

    resetCountdown() {
      clearInterval(this.timer)
      this.counting = false
      this.countdown = 60
      this.timer = null
    },

    async handleLogin() {
      const isEmailValid = this.validateEmail()
      const isCodeValid = this.validateCode()
      if (!isEmailValid || !isCodeValid) return

      try {
        uni.showLoading({ title: '登录中...' })
        await this.codeLogin({
          email: this.loginForm.email,
          captcha: this.loginForm.code,
          role: this.loginForm.role
        })
        uni.hideLoading()
        uni.showToast({
          title: `${this.loginForm.role === 'USER' ? '用户' : '企业'}登录成功`,
          icon: 'success'
        })
        this.$store.commit('SET_SHOW_TAB_BAR', true);
        // 直接使用switchTab，无需延迟
        uni.switchTab({ url: '/pages/index/index' });
      } catch (error) {
        uni.hideLoading()
        uni.showToast({ title: error || '登录失败', icon: 'none' })
      }
    },

    clearErrors() {
      this.errors = { email: '', code: '' }
    },

    goForgot() {
      uni.navigateTo({ url: '/pages/forgot/forgot-index/forgot-index' })
    },

    goRegister() {
      uni.navigateTo({ url: '/pages/register/register-index/register-index' })
    }
  },

  onUnload() {
    this.resetCountdown()
  }
}
</script>

<style scoped>
.container {
  margin: 100rpx;
}

.header {
  font-size: 48rpx;
  font-weight: bold;
  margin-bottom: 60rpx;
  text-align: center;
  margin-top: 15rpx;
}

.login-type-switch {
  display: flex;
  justify-content: center;
  margin-bottom: 40rpx;
}

.switch-container {
  display: flex;
  width: 400rpx;
  height: 70rpx;
  position: relative;
}

.switch-option {
  flex: 1;
  text-align: center;
  line-height: 70rpx;
  font-size: 28rpx;
  color: #666;
  position: relative;
  transition: all 0.3s ease;
}

.switch-option.active {
  color: #b6ccd8;
  font-weight: bold;
}

.switch-option.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 120rpx;
  height: 4rpx;
  background-color: #b6ccd8;
  border-radius: 2rpx;
}

.input-group {
  margin-bottom: 40rpx;
  position: relative;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #000;
  margin-bottom: 20rpx;
}

input {
  width: 100%;
  padding: 20rpx 0;
  border: none;
  font-size: 32rpx;
  outline: none;
  background: transparent;
  border-bottom: 2rpx solid #ccc;
}

.code-wrapper {
  display: flex;
  align-items: center;
  border-bottom: 2rpx solid #e0e0e0;
}

.code-btn {
  margin-left: 20rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #b6ccd8;
  border-radius: 10rpx;
  white-space: nowrap;
}

.code-btn:disabled {
  color: #ccc;
  background-color: #f5f5f5;
}

.error-message {
  position: absolute;
  bottom: -35rpx;
  left: 0;
  font-size: 24rpx;
  color: #ff4d4f;
}

.login-btn {
  width: 100%;
  margin-bottom: 30rpx;
  padding: 20rpx;
  font-size: 32rpx;
  color: #fff;
  background-color: #b6ccd8;
  border-radius: 70rpx;
  border: 2rpx solid #1d1c1c;
}

.ques {
  font-size: 24rpx;
  color: #999;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20rpx;
}

.divider {
  margin: 0 10rpx;
}

.footer {
  margin-top: 60rpx;
  font-size: 24rpx;
  color: #999;
  text-align: center;
}
</style>